import { SVGPathData } from 'svg-pathdata';
import arcToBezier from 'svg-arc-to-cubic-bezier';

const typeMap = {
  1: 'Z',
  2: 'M',
  4: 'H',
  8: 'V',
  16: 'L',
  32: 'C',
  64: 'S',
  128: 'Q',
  256: 'T',
  512: 'A',
};

/**
 * 简单解析SVG路径
 * @param d SVG path d属性
 */
export const parseSvgPath = (d: string) => {
  try {
    const pathData = new SVGPathData(d);

    const ret = pathData.commands.map(item => {
      return { ...item, type: typeMap[item.type] };
    });
    return ret;
  } catch (error) {
    console.warn('Failed to parse SVG path:', d, error);
    return [];
  }
};

export type SvgPath = ReturnType<typeof parseSvgPath>;

export interface SvgPoint {
  x: number;
  y: number;
  type?: string;
  close?: boolean;
  relative?: boolean;
  curve?: {
    type: 'cubic' | 'quadratic';
    x1: number;
    y1: number;
    x2?: number;
    y2?: number;
  };
}

export type SvgPoints = SvgPoint[];

/**
 * 解析SVG路径，并将圆弧（A）类型的路径转为三次贝塞尔（C）类型的路径
 * @param d SVG path d属性
 */
export const toPoints = (d: string): SvgPoints => {
  // 检查路径是否包含 undefined 值
  if (d.includes('undefined')) {
    console.warn('SVG path contains undefined values, skipping:', d);
    return [];
  }

  try {
    const pathData = new SVGPathData(d);
    const points: SvgPoints = [];

    for (const item of pathData.commands) {
      const type = typeMap[item.type];

      if (item.type === 2 || item.type === 16) {
        // M - 移动到, L - 直线
        points.push({
          x: item.x,
          y: item.y,
          relative: item.relative,
          type,
        });
      } else if (item.type === 32) {
        // C - 三次贝塞尔曲线
        points.push({
          x: item.x,
          y: item.y,
          curve: {
            type: 'cubic',
            x1: item.x1,
            y1: item.y1,
            x2: item.x2,
            y2: item.y2,
          },
          relative: item.relative,
          type,
        });
      } else if (item.type === 128) {
        // Q - 二次贝塞尔曲线
        points.push({
          x: item.x,
          y: item.y,
          curve: {
            type: 'quadratic',
            x1: item.x1,
            y1: item.y1,
          },
          relative: item.relative,
          type,
        });
      } else if (item.type === 512) {
        // A - 圆弧
        const lastPoint = points[points.length - 1];
        if (!lastPoint || !['M', 'L', 'Q', 'C'].includes(lastPoint.type || ''))
          continue;

        const cubicBezierPoints = arcToBezier({
          px: lastPoint.x as number,
          py: lastPoint.y as number,
          cx: item.x,
          cy: item.y,
          rx: item.rX,
          ry: item.rY,
          xAxisRotation: item.xRot,
          largeArcFlag: item.lArcFlag,
          sweepFlag: item.sweepFlag,
        });

        for (const cbPoint of cubicBezierPoints) {
          points.push({
            x: cbPoint.x,
            y: cbPoint.y,
            curve: {
              type: 'cubic',
              x1: cbPoint.x1,
              y1: cbPoint.y1,
              x2: cbPoint.x2,
              y2: cbPoint.y2,
            },
            relative: false,
            type: 'C',
          });
        }
      } else if (item.type === 1) {
        // Z - 闭合路径
        points.push({ x: 0, y: 0, close: true, type });
      } else {
        continue;
      }
    }

    return points;
  } catch (error) {
    console.warn('Failed to parse SVG path to points:', d, error);
    return [];
  }
};

/**
 * 获取SVG路径范围
 * @param d SVG path d属性
 */
export const getSvgPathRange = (d: string) => {
  try {
    const points = toPoints(d);
    if (points.length === 0) return { minX: 0, maxX: 0, minY: 0, maxY: 0 };

    const xs = points.map(point => point.x).filter(x => !isNaN(x));
    const ys = points.map(point => point.y).filter(y => !isNaN(y));

    return {
      minX: Math.min(...xs),
      maxX: Math.max(...xs),
      minY: Math.min(...ys),
      maxY: Math.max(...ys),
    };
  } catch (error) {
    console.warn('Failed to get SVG path range:', d, error);
    return { minX: 0, maxX: 0, minY: 0, maxY: 0 };
  }
};
